package com.ihr360.commons.specification;


import java.io.Serializable;

public class Ihr360Predication implements Serializable {

    private static final int STARTS_INDEX_OF_FIELD_NAME = 2;
    private static final String FILED_NAME_NOT_EQUAL_SYMBOAL = "_!";
    private static final String FILED_NAME_STARTWITH_SYMBOAL= "__";
    private static final String FILED_NAME_ENDWITH_SYMBOAL= "_";

    private String fieldName;
    private Object fieldValue;
    private PredicationOperator operator;
    private Ihr360EntityFieldType fieldType;

    public Ihr360Predication() {
    }

    public Ihr360Predication(String fieldName, Object fieldValue, PredicationOperator operator) {
        this.fieldName = fieldName;
        this.fieldValue = fieldValue;
        this.operator = operator;
    }

    public String getFieldName() {
        String name = fieldName;
        if (name.startsWith(FILED_NAME_NOT_EQUAL_SYMBOAL)) {
            name = name.substring(STARTS_INDEX_OF_FIELD_NAME);
        }
        if (name.startsWith(FILED_NAME_STARTWITH_SYMBOAL)){
            name = name.substring(STARTS_INDEX_OF_FIELD_NAME);
        }
        if (name.startsWith(FILED_NAME_ENDWITH_SYMBOAL)){
            name = name.substring(STARTS_INDEX_OF_FIELD_NAME - 1);
            return name;
        }
        if (name.endsWith(FILED_NAME_ENDWITH_SYMBOAL)){
            name = name.substring(0, name.length() - 1);
        }
        return name;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public Object getFieldValue() {
        return fieldValue;
    }

    public void setFieldValue(Object fieldValue) {
        this.fieldValue = fieldValue;
    }

    public PredicationOperator getOperator() {
        if (this.operator!=null){
            return this.operator;
        }
        if (fieldName.startsWith(FILED_NAME_NOT_EQUAL_SYMBOAL)) {
            return PredicationOperator.NOT_EQUALS;
        }
        if (fieldName.startsWith(FILED_NAME_STARTWITH_SYMBOAL)
                && fieldName.endsWith(FILED_NAME_ENDWITH_SYMBOAL)){
            return PredicationOperator.CONTAINS;
        }
        if (fieldName.startsWith(FILED_NAME_STARTWITH_SYMBOAL)){
            return PredicationOperator.START_WITH;
        }
        if (fieldName.endsWith(FILED_NAME_ENDWITH_SYMBOAL)){
            return PredicationOperator.END_WITH;
        }
        return PredicationOperator.EQUALS;
    }

    public void setOperator(PredicationOperator operator) {
        this.operator = operator;
    }

    public Ihr360EntityFieldType getFieldType() {
        return fieldType;
    }

    public void setFieldType(Ihr360EntityFieldType fieldType) {
        this.fieldType = fieldType;
    }
}